package ge.telasi.tasks.ui.task;

import ge.telasi.tasks.model.TaskAttachment;
import ge.telasi.tasks.model.Task;
import ge.telasi.tasks.model.validation.FileValidator;
import ge.telasi.tasks.ui.Platform;
import ge.telasi.tasks.ui.PrefUtils;
import ge.telasi.tasks.ui.UIUtils;
import ge.telasi.tasks.ui.comp.TableUtils;
import ge.telasi.tasks.ui.log.LoggerUtils;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

/**
 * @author dimitri
 */
public class AttachmentPanel extends JPanel {
    private static final long serialVersionUID = -7127170277170008200L;
    AttachmentTable table;
    Task task;

    public AttachmentPanel() {
        initComponents();
        setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    }

    private void initComponents() {
        setLayout(new BorderLayout(5, 5));
        table = new AttachmentTable();
        add(new JScrollPane(table), BorderLayout.CENTER);
        JPanel jPanel1 = new JPanel(new BorderLayout(5, 5));
        JButton btnAdd = new JButton("ახლის დამატება", UIUtils.getIcon16x16("package_add.png"));
        JButton btnDownload = new JButton("გადმოწერა", UIUtils.getIcon16x16("disk.png"));
        JButton btnRemove = new JButton(UIUtils.getIcon16x16("delete.png"));
        JPanel jPanel2 = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 0));
        jPanel2.add(btnAdd);
        jPanel2.add(btnDownload);
        jPanel1.add(jPanel2, BorderLayout.WEST);
        jPanel1.add(btnRemove, BorderLayout.EAST);
        add(jPanel1, BorderLayout.SOUTH);
        JLabel title = new JLabel("მიმაგრებული ფაილების სია:");
        add(title, BorderLayout.NORTH);
        btnAdd.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onAddAttachement();
            }
        });
        btnRemove.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onRemoveAttachment();
            }
        });
        btnDownload.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onDownload();
            }
        });
    }

    public Task getTask() {
        return task;
    }

    public void setTask(Task task) {
        this.task = task;
        table.display(task.getAttachments());
    }

    private void onAddAttachement() {
        JFileChooser chooser = new JFileChooser();
        try {
            chooser.setCurrentDirectory(new File(PrefUtils.getString("attachement_last_folder")));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
//        chooser.setDialogTitle("აარჩიეთ დასამატებელი ფაილი");
        chooser.setDialogType(JFileChooser.FILES_ONLY);
        int resp = chooser.showDialog(this, "აარჩიეთ");
        if (resp == JFileChooser.APPROVE_OPTION) {
            try {
                java.io.File file = chooser.getSelectedFile();
                PrefUtils.putString("attachement_last_folder", file.getParent());
                long length = file.length();
                new FileValidator().validateLength(length);
                if (Platform.getDefault().validateConnection()) {
                    byte[] data = new byte[(int) length];
                    FileInputStream in = new FileInputStream(file);
                    in.read(data);
                    in.close();
                    TaskAttachment binaryData = new TaskAttachment();
                    binaryData.setName(file.getName());
                    Platform pl = Platform.getDefault();
                    binaryData = pl.getFacade().uploadAttachment(pl.getCredentials(), task, binaryData, data);
                    if (task != null) {
                        task.addAttachment(binaryData);
                        fireTaskChange();
                        TableUtils.setSelectionAtEnd(table);
                    } else {
                        table.add(binaryData);
                    }
                    data = null;
                }
            } catch (Exception ex) {
                LoggerUtils.manageException(this, ex);
            } finally {
                System.gc();
            }
        }
    }

    private void onRemoveAttachment() {
        List<TaskAttachment> attachments = table.getSelections();
        if (attachments != null && !attachments.isEmpty()) {
            if (Platform.getDefault().validateConnection()) {
                Platform pl = Platform.getDefault();
                String msg = pl.getLocaleManager().getMessage("General.deleteByCountMsg", attachments.size());
                if (UIUtils.askConfirmation(table, msg)) {
                    try {
                        pl.getFacade().removeAttachment(pl.getCredentials(), attachments);
                        for (TaskAttachment attachment : attachments) {
                            table.remove(attachment);
                            if (task != null) {
                                task.removeAttachment(attachment);
                            }
                        }
                        if (task != null) {
                            fireTaskChange();
                        }
                    } catch (Exception ex) {
                        LoggerUtils.manageException(this, ex);
                    }
                }
            }
        }
        
    }

    private void onDownload() {
        TaskAttachment data = table.getSelection();
        Platform pl = Platform.getDefault();
        if (data == null || !pl.validateConnection()) {
            return;
        }
        JFileChooser chooser = new JFileChooser();
        try {
            chooser.setCurrentDirectory(new File(PrefUtils.getString("download_last_folder")));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setDialogTitle("აარჩიეთ საქაღალდეში რომელშიც უნდა შეინახოთ ფაილი");
        int resp = chooser.showDialog(this, "არჩევა");
        if (resp == JFileChooser.APPROVE_OPTION && chooser.getSelectedFile() != null) {
            File dir = chooser.getSelectedFile();
            PrefUtils.putString("download_last_folder", dir.getAbsolutePath());
            if (!dir.exists()) {
                dir.mkdirs();
            }
            try {
                File f = new File(dir, data.getName());
                if (!f.exists()) {
                    f.createNewFile();
                } else {
                    boolean owerwrite = UIUtils.askConfirmation(this, "ფაილი ამ სახელით უკვე არსებობს. გინდათ მისი გადაწერა?");
                    if (!owerwrite) return;
                }
                byte[] bytes = pl.getFacade().downloadAttachment(pl.getCredentials(), task, data);
                OutputStream out = new FileOutputStream(f);
                out.write(bytes);
                out.flush();
                out.close();
            } catch (Exception ex) {
                LoggerUtils.manageException(this, ex);
            }
        }
    }

    public List<TaskAttachment> getAttachments() {
        return table.getFullData();
    }

    protected void fireTaskChange() {
        firePropertyChange("task", "dummy old value", task);
    }
    
}
